package main

import (
	"blog_test/src/global"
	"blog_test/src/internal/model"
	"blog_test/src/internal/routers"
	"blog_test/src/pkg/logger"
	"blog_test/src/pkg/setting"
	"fmt"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"net/http"
	"time"
)

func init() {
	err := setupSetting()
	if err != nil {
		log.Fatalf("init setupSetting err: %v", err)
	}

	err = setupLogger()
	if err != nil {
		log.Fatalf("init setupLogger err: %v", err)
	}
	err = setupDBEngin()
	if err != nil {
		log.Fatalf("init setupDBEngine err : %v", err)
	}
}

func main() {

	global.Logger.Infof("%s: go-programming-tour-book/%s", "eddycjy", "blog-service")
	router := routers.NewRouter()
	s := &http.Server{
		Addr:    ":" + global.ServerSetting.HttpPort,
		Handler: router,
	}
	s.ListenAndServe()
}

func setupSetting() error {
	setting, err := setting.NewSetting()
	if err != nil {
		return err
	}
	err = setting.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}
	err = setting.ReadSection("App", &global.AppSetting)
	if err != nil {
		return err
	}

	err = setting.ReadSection("Database", &global.DatabaseSetting)
	if err != nil {
		return err
	}
	global.ServerSetting.ReadTimeout *= time.Second
	fmt.Println(global.ServerSetting)

	fmt.Println(global.DatabaseSetting)
	return nil

}

func setupDBEngin() error {
	var err error
	global.DBEngine, err = model.NewDBEngine(global.DatabaseSetting)
	if err != nil {
		return err
	}
	return nil

}

func setupLogger() error {
	fileName := global.AppSetting.LogSavePath + "/" + global.AppSetting.LogFileName + global.AppSetting.LogFileExt
	global.Logger = logger.NewLogger(&lumberjack.Logger{
		Filename:  fileName,
		MaxSize:   600,
		MaxAge:    10,
		LocalTime: true,
	}, "", log.LstdFlags).WithCaller(2)
	return nil
}
